package com.leoman.controller.backend;

import com.leoman.common.DataTableFactory;
import com.leoman.controller.common.CommonController;
import com.leoman.entity.VideoType;
import com.leoman.service.VideoService;
import com.leoman.service.VideoTypeService;
import com.leoman.utils.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 视频分类管理
 * Created by 涂奕恒 on 2016/10/24.
 */
@Controller
@RequestMapping(value = "backend/videoType")
public class VideoTypeController extends CommonController {

    @Autowired
    private VideoTypeService videoTypeService;

    @Autowired
    private VideoService videoService;

    @RequestMapping("index")
    public String index() {
        return "backend/分类列表";
    }

    @RequestMapping("/list")
    public void list(HttpServletResponse response,
                     Integer draw,
                     Integer start,
                     Integer length) {
        if (null == start || start == 0) {
            start = 1;
        }
        int pageNum = getPageNum(start, length);
        Page<VideoType> page = videoTypeService.find(pageNum, length);

        for (VideoType videoType : page.getContent()) {
            videoType.setVideoNum(videoService.findListByVideoTypeId(videoType.getId()).size());
        }

        Map<String, Object> result = DataTableFactory.fitting(draw, page);
        WebUtil.printJson(response, result);
    }

    /**
     * 新增 or 编辑分类信息
     *
     * @param videoTypeId      分类ID
     * @param name             分类名称
     * @param multipartRequest 分类封面
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public Integer save(Integer videoTypeId, String name, MultipartRequest multipartRequest) {
        try {
            return videoTypeService.saveVideoType(videoTypeId, name, multipartRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 删除分类信息
     *
     * @param videoTypeId 分类ID
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Integer delete(Integer videoTypeId) {
        try {
            return videoTypeService.deleteVideoTypeId(videoTypeId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
